from src.util.Service import *


# 获取用户组数据
def getGroup(page: Page = Page(), cdn: dict = None):
    if cdn is None:
        cdn = {}
    return Group.getGroupAll(page, cdn)


# 删除用户组
def delGroup(ids: list[int]):
    try:
        database.begin()
        Group.delGroup(ids)
        GroupUser.delGroupUserInGid(ids)
        GroupAuth.clearAuth(ids)
        database.commit()
        return True
    except:
        database.rollback()
        return False


# 添加用户组
def addGroup(data: dict):
    data['createTime'] = datetime.utcnow()
    data['status'] = '1'
    try:
        return Group.addGroup(data)
    except:
        return False


# 更新组信息
def updateGroup(data: dict):
    data = formatParam(data, ['createTime', 'createBy'])
    if not authParam(data.get('status'), ['1', '0']):
        return False
    data['updateTime'] = datetime.utcnow()
    try:
        Group.updateGroup(data)
        return True
    except:
        return False


# 获取用户组用户
def getGroupUser(gid: int):
    return GroupUser.getGroupUserByGid(gid)


# 更新用户组的用户
def updateGroupUser(gid: int, uids: list[int], uid):
    try:
        database.begin()
        GroupUser.delGroupUserInGid([gid])
        GroupUser.addGroupUser(uids, gid)
        data = {'id': gid, 'updateTime': datetime.utcnow(), 'updateBy': uid}
        Group.updateGroup(data)
        database.commit()
        return True
    except:
        database.rollback()
        return False


# 获取用户组权限
def getGroupAuth(gid: int, type: str):
    return GroupAuth.getAuth([gid], type)


# 更新用户组权限
def updateGroupAuth(gid: int, type: str, data: list, uid):
    if not authParam(type, ['route', 'menu', 'button']):
        return False
    try:
        database.begin()
        GroupAuth.delAuth(gid, type)
        GroupAuth.addAuth(gid, type, data)
        data = {'id': gid, 'updateTime': datetime.utcnow(), 'updateBy': uid}
        Group.updateGroup(data)
        database.commit()
        return True
    except:
        database.rollback()
        return False
